package cn.edu.tsinghua.training.cms.demo.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import cn.edu.tsinghua.training.cms.demo.entity.Channel;
import cn.edu.tsinghua.training.cms.demo.service.ChannelService;

@Results({
	@Result(name="add_success", location="channel_list", type="redirectAction"),
	@Result(name="list_success", location="/channel/channel_list.jsp", type="redirect"),
	@Result(name="search_success", location="/channel/channel_edit.jsp", type="redirect"),
	@Result(name="update_success", location="channel_list", type="redirectAction"),
	@Result(name="remove_success", location="channel_list", type="redirectAction"),
	@Result(name="channel_article_list_success", location="/article/article_list.jsp", type="redirect")
})
public class ChannelAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Channel channel;
	@Autowired
	private ChannelService channelService;
	private static final int PAGE_SIZE = 5;
	private int page;

	@Action("channel_add")
	public String add() throws Exception {
		channelService.add(channel);
		return "add_success";
	}

	@Action("channel_list")
	public String list() throws Exception {
		getSession().put("pageBean", channelService.list(PAGE_SIZE, page));
		return "list_success";
	}
	
	@Action("channel_search")
	public String search() throws Exception {
		getSession().put("channel", channelService.queryById(channel.getId()));
		return "search_success";
	}
	
	@Action("channel_update")
	public String update() throws Exception {
		channelService.update(channel);
		return "update_success";
	}
	
	@Action("channel_remove")
	public String remove() throws Exception {
		Channel channel = channelService.queryById(this.channel.getId());
		channel.setStatus(-1);
		channelService.update(channel);
		return "remove_success";
	}	
	
	@Action("channel_article_list")
	public String channelArticleList() throws Exception {
		String hql = "from Channel c left outer join fetch c.articles where c.id=:channelid";
		String[] paramNames = {"channelid"};
		if (channel == null) {
			this.channel = (Channel) getSession().get("channel");
		}
		Object[] values = {channel.getId()};
		getSession().put("channel", channelService.query(hql, paramNames, values).get(0));
		return "channel_article_list_success";
	}

	public Channel getChannel() {
		return channel;
	}

	public void setChannel(Channel channel) {
		this.channel = channel;
	}

	public void setPage(int page) {
		this.page = page;
	}

}
